package com.example.luozizhao.eprxdemo.http;


import com.example.luozizhao.eprxdemo.commom.ServerUrl;
import com.example.luozizhao.eprxdemo.http.api.ApiService;
import com.example.luozizhao.eprxdemo.http.cookie.AddCookiesInterceptor;
import com.example.luozizhao.eprxdemo.http.cookie.ReceivedCookiesInterceptor;
import com.example.luozizhao.eprxdemo.net.bean.face.TokenRespon;
import com.example.luozizhao.eprxdemo.net.response.GetNounceRespBean;
import com.example.luozizhao.eprxdemo.net.response.login.UserLoginRespBean;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.Map;

import javax.inject.Scope;

import io.reactivex.Observable;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.PUT;

/**
 * Created by luozizhao on 2018/4/23.
 */


public class RetrofitHelper implements ApiService {

    private ApiService mApi;
    private static RetrofitHelper mInstance;
    private  Retrofit build;
    private final Retrofit mRetroBuild;

    public RetrofitHelper() {

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new AddCookiesInterceptor())
                .addInterceptor(new ReceivedCookiesInterceptor())
                //可以增加连接时间什么的
                .build();


        Gson gson  = new GsonBuilder().setLenient().create();

        mRetroBuild = new Retrofit.Builder()
                .baseUrl(ServerUrl.SERVER_ADDRESS)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();

        mApi = mRetroBuild.create(ApiService.class);
    }


    public static RetrofitHelper getInstance(){
        if (mInstance==null) {
            synchronized (RetrofitHelper.class){
                if (mInstance==null){
                    mInstance = new RetrofitHelper();
                }
            }
        }
        return mInstance;
    }

    @Override
    public Observable<GetNounceRespBean> getTattedCode() {
        return mApi.getTattedCode();
    }


    @Override
    public Observable<UserLoginRespBean> login(Map<String, String> params) {
        return mApi.login(params);
    }

    @Override
    public Observable<TokenRespon> getToken(String type, String api_key, String secret_Key) {
        return mApi.getToken(type,api_key, secret_Key);
    }


}
